<template>
	<el-drawer v-model="drawer" :with-header="false" @close="close" :append-to-body="true" :size="size" ref="drawerRef"
		class="customer-detail-drawer" :modal="true" modal-class="customer-modal" >

		<div class="app-container">
			<el-tabs v-model="activeName" class="demo-tabs">
				<!-- <el-tab-pane label="定义题目" name="first"></el-tab-pane>
				<el-tab-pane label="详情" name="second"></el-tab-pane> -->
			</el-tabs>
			<div v-if="activeName == 'first'">
				<div>
					<el-button type="primary" size="small" @click="openDialogQuestion">从题库添加</el-button>
					<el-button type="primary" size="small" @click="addQuestion">新增</el-button>
				</div>
				<div style="margin-top: 20px;">
					<el-table :data="tableData" style="width: 100%" size="small">
						<el-table-column label="题号即(排序)1,2,3" prop="indexLetter">
							<template #default="scope">
							<el-input-number size="small" v-model="scope.row.indexLetter" :min="0" @change="updateIndexLetter(scope.row)"></el-input-number>
						</template>
						</el-table-column>
						<el-table-column label="名称" prop="name"></el-table-column>
						<el-table-column label="题型" prop="type">
							<template #default="scope">
								<template v-for="item in typeOptions">
									<el-tag effect="plain" v-if="item.value == scope.row.type" size="small">{{
											item.label
									}}</el-tag>
								</template>
							</template>
						</el-table-column>
						<el-table-column label="备注" prop="descs"></el-table-column>
						<el-table-column label="操作" align="center" fixed="right">
                            <template #default="scope">
                                <el-button type="primary" link size="small" @click="delRow(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
					</el-table>
				</div>
			</div>


			<div class="answer_page" v-if="activeName == 'second'">
				<el-card style="position: relative" class="answer_card">
					<template v-for=" questionItems in questionList">
						<!--          <div v-for="(item, index) in questionList" :key="item.id" :ref="'answer'+index">-->
						<div class="title_box">
							<div class="answer_num">
								{{ questionItems && questionItems.indexLetter }}. {{ getQuestionType(questionItems) }}（{{
										questionItems.score
								}}分）
							</div>
							<div class="answer_question">
								<div class="htmlPage" style="background:rgb(247, 248, 249);padding:12px 15px;"
									v-html="questionItems.subName || questionItems.name" ></div>
							</div>
						</div>
						<div class="answer_content_box">
							<el-form label-width="85px" v-if="questionItems.type != 2 && questionItems.type != 3">
								<el-form-item>
									<div v-for="choice in questionItems.qnChoices" :key="choice.id" class="choice-row"
										v-html="choice.indexLetter + '. ' + choice.content" >
									</div>
								</el-form-item>
							</el-form>
							<br>
						</div>
					</template>
				</el-card>
			</div>
		</div>



		<!-- 选择题目 -->

		<el-dialog v-model="dialogQuestionVisible" title="从题库选题">
			<el-transfer v-model="leftValue" style="text-align: left; display: inline-block" :titles="['题目', '已选择题目']"
				:format="{
					noChecked: '${total}',
					hasChecked: '${checked}/${total}',
				}" :props="{
	key: 'id',
	label: 'name',
}" :data="data" @change="handleChange">
			</el-transfer>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogQuestionVisible = false" size="small">取 消</el-button>
					<el-button type="primary" @click="confirmSelect" size="small">
						确 认
					</el-button>
				</div>
			</template>
		</el-dialog>

		<question-detail v-model:dialogDrawer="dialogFormVisible" :defaultForm="questionform" :title="title"
            @onDetailSubmit="onDetailSubmit" :categoryOptions="treeData"></question-detail>

		<div class="tabs-list">
			<div class="close-btn" @click="close">
				<el-icon color="var(--next-color-white)" size="28px">
					<ele-CircleClose />
				</el-icon>
			</div>
		</div>
	</el-drawer>
</template>

<script>
import {
	toRefs,
	computed,
	reactive,
	watch,
	onMounted,
	ref,
	nextTick
} from 'vue'
import { getQuestionnaierList } from '/@/api/qn/paper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getList as getSelectQuestionList,savePaperQuestions,create, update , remove} from '/@/api/qn/question'
import { getList as getCategoryList } from '/@/api/qn/category'
import QuestionDetail from './QuestionDetail.vue'
export default {
	name: 'PaperRelationQuestionDetail',
	components: {
        QuestionDetail
    },
	props: {
		dialogDrawer: {
			type: Boolean,
			default: false
		},
		defaultForm: {
			type: Object,
			default() {
				return {}
			}
		},
		activeName: {
			type: String,
			default: 'first'
		}
	},
	emits: ['update:dialogDrawer'],
	setup(props, context) {
		const { defaultForm, activeName } = toRefs(props)
		const searchHistoryForm = ref()
		const state = reactive({
			form: {},
			showCard: false,
			questionList: [],
			// activeName: 'first',
			tableData: [],
			data: [],
			leftValue: [],
			dialogQuestionVisible: false,
			dialogFormVisible:false,
			treeData:[],
			title:'',
			questionform:{},
			typeOptions: [{
				value: '1',
				label: '单选',
			},
			{
				value: '2',
				label: '填空',
			},
			{
				value: '3',
				label: '简答题',
			}, {
				value: '4',
				label: '判断',
			}, {
				value: '5',
				label: '多选',
			}],
		})

		const {
			dialogDrawer
		} = toRefs(props)
		let drawer = computed({
			get: () => dialogDrawer.value,
			set: (val) => {
				context.emit('update:dialogDrawer', val)
			}
		})
		watch(() => dialogDrawer.value, val => {
			context.emit("update:dialogDrawer", val)
			if (val) {
				nextTick(() => {
					getList()
					if (document.querySelector('.el-drawer__body')) {
						document.querySelector('.el-drawer__body').onscroll = e => {
							state.scrollTop = e.target.scrollTop
						}
					}
					if (document.querySelector('.refLine')) {
						state.refLineTop = document.querySelector('.refLine').offsetTop
					}
				})
			}
		})
		const getSize = () => {
			if (document.body.clientWidth <= 1400) {
				return '1220px'
			} else {
				return '85%'
			}
		}

		state.size = getSize()
		const close = () => {
			context.emit("update:dialogDrawer", false)
		}
		const searchHistorySubmit = () => {
			state.searchHistory.current = 1

		}
		const getList = () => {
			getQuestionnaierList({
				paperId: defaultForm.value.id,
				showAnswer: 1
			}).then(res => {
				state.questionList = res.data
				state.tableData = res.data
			})
		}
		const handleSizeChange = () => {

		}
		const handleCurrentChange = e => {
			state.current = e

		}
		const reset = (formEl) => {


		}
		const getQuestionType = (item) => {
			let result = '单选题'
			switch (item.type) {
				case 2: {
					result = '填空题'
					break
				}
				case 3: {
					result = '简答题'
					break
				}
				case 4: {
					result = '判断题'
					break
				}
				case 5: {
					result = '多选题'
				}
			}
			return result
		}

		const handleChange = () => {
		}
		const openDialogQuestion = () => {
			state.dialogQuestionVisible = true
			state.leftValue = []
			getSelectQuestionList({ paperId: '0' }).then(res => {
				state.data = res.data
			})
		}
		const confirmSelect = () => {
			if (state.leftValue.length > 0) {
				let result = []
				for (let id of state.leftValue) {
					for (let q of state.data) {
						if (id == q.id) {
							q.paperId = defaultForm.value.id
							result.push(q)
						}
					}
				}
				savePaperQuestions(result).then(res=>{
					getList()
					state.dialogQuestionVisible = false
				})

			} else {
				ElMessage({
					type: 'error',
					message: '请选择题目',
				})
			}
		}
		const updateIndexLetter = (data) => {
			update(data).then(res => {
				if (res.code == 0) {
					getList()
					ElMessage.success("修改成功");
				} else {
					ElMessage.error("修改失败");
				}
			})
		}
		const getCategory = () => {
            getCategoryList().then(res=>{
                state.treeData = res.data
            })
        }
		const onDetailSubmit = () => {
			state.dialogFormVisible = false
			getList()
		}
		const addQuestion = () => {
			getCategory()
			state.dialogFormVisible = true
			state.title = '添加题目'
			state.questionform = {
				id: null,
				paperId: defaultForm.value.id,
                type: '',
                name: null,
                descs: null,
                qnChoices: [{
                    orderNo: 1,
                    indexLetter: 'A',
                    content: null
                }]
			}
		}
		const delRow = row => {
            ElMessageBox.confirm(
                '是否确认删除名称为"' + row.name + '"的数据项？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                remove(row.id).then(res => {
                    if (res.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getList()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '删除失败：' + res.message,
                        })
                    }
                })

            }).catch()
        }
		onMounted(() => {

		})
		return {
			drawer,
			...toRefs(state),
			close,
			searchHistoryForm,
			searchHistorySubmit,
			getList,
			handleSizeChange,
			handleCurrentChange,
			reset,
			getQuestionType,
			handleChange,
			openDialogQuestion,
			confirmSelect,
			updateIndexLetter,
			onDetailSubmit,
			getCategory,
			addQuestion,
			delRow,
			activeName
		}
	}
}
</script>

<style lang="scss">
.customer-detail-drawer {
	overflow: unset;
	position: fixed;
}

.customer-modal {
	//left: unset;
}

.action-popper {
	background: transparent !important;
	position: relative;

	&:after {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: var(--el-color-primary-light-9);
		opacity: .8;
		filter: grayscale(100%);
	}

	.el-popper__arrow::before {
		background: var(--el-color-primary-light-9) !important;
		opacity: .8;
		filter: grayscale(100%);
	}

	.sale-title {
		color: var(--el-text-color-primary);
	}
}

.tabs-list {
	position: absolute;
	top: 90px;
	left: -50px;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	overflow: auto;
	max-height: 100%;

	// .tabs-cell{
	//     background: var(--next-color-white);
	//     margin-bottom: 3px;
	//     min-width: 60px;
	//     text-align: right;
	//     padding: 0 5px;
	//     cursor: pointer;
	//     font-size: 12px;
	//     border-radius: 5px 0 0 5px;
	//     box-shadow: rgba(0, 0, 0, 0.15) -1.95px -1.95px 2.6px;
	//     color: var(--el-text-color-secondary);
	//     transition: .1s;
	//     min-height: 35px;
	//     display: flex;
	//     flex-direction: column;
	//     align-items: center;
	//     justify-content: center;
	//     filter: brightness(.85);
	// }
	// .tabs-cell:hover,
	// .active{
	//     background: var(--el-color-primary-dark-2);
	//     color: var(--el-color-primary-light-9);
	//     padding: 5px 8px;
	//     min-width: 70px;
	//     font-size: 14px;
	//     font-weight: bold;
	//     filter: brightness(1)
	// }
	.close-btn {
		width: 50px;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		background: var(--el-color-primary);
		padding: 5px 0;
		border-radius: 5px 0 0 5px;
	}
}

.company-title {
	text-align: center;
	font-size: 18px;
	color: var(--next-bg-menuBar-light-1);
	margin-bottom: 50px;
}

.app-container {
	// margin-top: 3px;
	background: #f9f9f9;
	min-height: calc(100vh - 95px);

	.question_header {
		background: #fff;
		padding: 20px;
		margin: 0 auto 10px;
		max-width: 1200px;
		border-radius: 16px;
		box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.answer_page {
		display: flex;
		align-items: flex-start;
		max-width: 1200px;
		margin: 0 auto;

		.title_box {
			//display: flex;
			align-items: flex-start;

			.answer_num {
				//width: 40px;
				font-weight: bold;
				font-size: 16px;
			}

			.answer_question {
				//flex: 1;
				overflow: hidden;
			}
		}

		.answer_card {
			flex: 1;
			overflow: hidden;
			margin-right: 10px;

			.answer_content_box {
				margin: 20px 0 20px 40px;
				border-bottom: 1px solid #eee;
			}
		}

		.question_card {
			width: 280px;
			position: sticky;
			top: 130px;

			.question_num_content {
				display: flex;
				align-items: center;
				flex-wrap: wrap;

				.question_num {
					width: 35px;
					height: 35px;
					margin: 0 15px 12px 0;
					border-radius: 8px;
					border: 1px solid #eee;
					cursor: pointer;
					font-size: 14px;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.question_num:hover {
					background: #409EFF;
					color: #fff;
					border-color: #409EFF;
				}

				.question_num:nth-child(5n+5) {
					margin-right: 0;
				}

				.success {
					background: rgba(#67C23A, .1);
					border-color: #67C23A;
					color: #67C23A;
				}

				.error {
					background: rgba(#F56C6C, .1);
					border-color: #F56C6C;
					color: #F56C6C;
				}
			}
		}

		.fixed_answer_icon {
			display: none;
		}

		@media screen and(max-width: 750px) {
			.answer_card {
				margin-right: 0;
			}

			.question_card {
				position: fixed;
				z-index: 99;
				top: unset;
				bottom: -100vh;
				width: 90%;

				.question_num_content {
					.question_num {
						margin-right: 12px;
					}

					.question_num:nth-child(5n+5) {
						margin-right: 12px;
					}
				}
			}

			.question_fixed_active {
				top: unset;
				bottom: 0;
				transition: .2s;
			}

			.fixed_answer_icon {
				display: block;
				position: fixed;
				width: 48px;
				height: 48px;
				background: #409EFF;
				z-index: 99;
				top: 40%;
				right: 0;
				border-radius: 8px 0 0 8px;
				display: flex;
				align-items: center;
				justify-content: center;

				i {
					font-size: 24px;
					color: #fff;
				}
			}
		}
	}
}

:deep(.el-image__error) {
	font-size: 12px;
}

.choice-row {
	margin: 3px 0;
	padding: 9px 15px;
	background: rgb(247, 248, 249);
}

.green-row {
	background-color: rgba(103, 194, 58, 0.5);
}

.red-row {
	background-color: rgba(245, 108, 108, 0.5);
}

// 答题卡小圆点
.dot {
	display: inline-block;
	width: 6px;
	height: 6px;
	border-radius: 50%;
}

.title_label {
	height: 40px;
	line-height: 40px;
}

.htmlPage {
    :deep(img) {
		width: 100% !important;
		height: 200px !important;
		object-fit: contain;
	}
}
</style>
